<?php if(!defined('BASEPATH')) exit('No direct script access allowed');

require APPPATH . '/libraries/BaseController.php';
/**
 * Class : User (UserController)
 * User Class to control all user related operations.
 * @author : Kishor Mali
 * @version : 1.1
 * @since : 15 November 2016
 */
class AmazonOrder extends BaseController
{
    /**
     * This is default constructor of the class
     */
    public function __construct()
    {
        parent::__construct();
        $this->load->model('amazonOrder_model');
        $this->isLoggedIn();   
        $this->load->helper(array('form', 'url'));
    }

    public function index($page = 1){
        $number = 10;
        $this->global['pageTitle'] = '亚马逊下单管理';
        $orders = $this->amazonOrder_model->getOrders($number, ($page - 1) * $number);
        $this->loadViews("amazonOrder/orderList", $this->global, array(
            'error' => ' ',
            'orders' => $orders
        ) , NULL);

    }

    public function detail($order_id){
        $order = $this->amazonOrder_model->getOrder($order_id);

        $this->global['pageTitle'] = '亚马逊订单查看';
        $this->loadViews("amazonOrder/orderView", $this->global, array(
            'error' => ' ',
            'details' => $this->createExcelData($order),
            'order' => $order,
            'mergeCells' => '[]'
        ) , NULL);


    }

    public function deleteOrder() {
        $order_id = $this->input->post('id');
        $this->amazonOrder_model->deleteOrder($order_id);
        $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode(array('code' => '200', 'message' => $order_id)));
    }

    public function uploadExcel() {
        $config['upload_path']      = './uploads/';
        $config['allowed_types']    = 'gif|jpg|png|txt|xlsx|xls|csv';
        $config['max_size']     = 1024 * 10;
        $config['max_width']        = 1024 * 10;
        $config['max_height']       = 768 * 10;
        $config['encrypt_name'] = true;

        $this->load->library('upload', $config);
        $this->global['pageTitle'] = 'CodeInsect : Upload';

        if ( ! $this->upload->do_upload('amazonOrderExcel'))
        {
            // 上传失败
            // $error = array('error' => $this->upload->display_errors(), 'upload_data' => $this->upload->data());

            // $this->loadViews('upload/index', $this->global, $error);
            $this->output->set_status_header(400);
        }
        else
        {
            // 上传成功
            try {
                $this->compile_excel($this->upload->data('full_path'));
                $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode(array('code' => '200', 'message' => 'OK')));
            } catch(Exception $e) {
                $this->output->set_status_header(400);
            }

            // $data = array('upload_data' => $this->upload->data());
            
            // $this->loadViews('upload/upload_success', $this->global, $data);
        }
    }


    private function compile_excel($file_path) {
        $this->load->library("hei_excel");
        $this->global['pageTitle'] = 'CodeInsect : Excel';
        $option = array(
            'mergeCells' => [],
            'formula' => [],
            'format'=> []
        );
        $data = $this->hei_excel->importExcel($file_path, 0, 0, $option);

        $order = array(
            'details' => array()
        );
        foreach (array_values($data) as $key => $value) {
            if($key != 0 && $key != sizeof($data) - 1) {
                $value = array_values($value);
                array_push($order['details'], array(
                    'time_for_purchase' => $value[0],
                    'purchasing_agent'  => $value[1],
                    'time_for_delivery' => $value[2],
                    'spec_no'           => $value[3],
                    'goods_name'        => $value[4],
                    'asin'              => $value[5],
                    'quantity'          => $value[6],
                    'price'             => $value[7],
                    'total'             => $value[8],
                    'gift_box_size'     => $value[9],
                    'carton_size'       => $value[10],
                    'piece_weight'      => $value[11],
                    'package_weight'    => $value[12],
                    'weight'            => $value[13],
                    'amount_per_box'    => $value[14],
                    'amount_box'        => $value[15],
                    'remark'            => $value[16]
                ));
            }
                
        }
        $this->load->model('amazonOrder_model');
        $this->amazonOrder_model->createOrder($order);
        return TRUE;
        // $this->amazonOrder_model->deleteOrder(1);
        // $res = $this->amazonOrder_model->getOrders(10, 0);
        // $res = $this->amazonOrder_model->getOrder(2);
        // echo "<pre>";
        // print_r($data);
        // return;
        
        // $this->loadViews('upload/excel_view', $this->global, array(
        //     'data' => $data, 
        //     'mergeCells' => $this->jsonArray($option['mergeCells']),
        //     'file' => $fileName
        // ));

    }

    private function createExcelData($order){
        $data = array();
        array_push($data, array(
            'A' => '采购时间',
            'B' => '采购人',
            'C' => '交货时间',
            'D' => '型号',
            'E' => '产品名称',
            'F' => 'ASIN',
            'G' => '采购数量',
            'H' => '单价＄',
            'I' => '总价＄',
            'J' => '彩盒尺寸mm',
            'K' => '外箱尺寸mm',
            'L' => '单件重量KG',
            'M' => '每箱重量KG',
            'N' => '总重量KG',
            'O' => '每箱数量',
            'P' => '箱数',
            'Q' => '其他说明',
        ));

        foreach ($order->details as $key => $x) {
            array_push($data, array(
                'A' => $x->time_for_purchase,
                'B' => $x->purchasing_agent,
                'C' => $x->time_for_delivery,
                'D' => $x->spec_no,
                'E' => $x->goods_name,
                'F' => $x->asin,
                'G' => $x->quantity,
                'H' => $x->price,
                'I' => $x->total,
                'J' => $x->gift_box_size,
                'K' => $x->carton_size,
                'L' => $x->piece_weight,
                'M' => $x->package_weight,
                'N' => $x->weight,
                'O' => $x->amount_per_box,
                'P' => $x->amount_box,
                'Q' => $x->remark,
            ));
        }


        array_push($data, array(
            'A' => '',
            'B' => '',
            'C' => '',
            'D' => '',
            'E' => '汇总',
            'F' => '',
            'G' => '',
            'H' => '',
            'I' => '2100',
            'J' => '',
            'K' => '',
            'L' => '',
            'M' => '',
            'N' => '385',
            'O' => '',
            'P' => '',
            'Q' => '',
        ));
        return $data;
    }
    
}

?>